package com.tanggh.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 工具类 处理项目中一些字符转换，格式问题
 * 
 * @author sunday
 * 
 */
public class Tools {
	
	/**
	 * 转化浏览器地址栏中文字符
	 * 
	 * @param str
	 * @return
	 */
	public static String convertCode(String str){
		// resin4 无需转码
//		try {
//			if(null != str && !"".equals(str)){
//				return new String(str.getBytes("iso-8859-1"), "UTF-8");				
//			}
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		}
//		return "";
		return str;
	}

	/**
	 * 处理字符串，null返回"" 该方法不会返回null
	 * 
	 * @param input
	 * @return
	 */
	public static String toTrim(String input) {
		if (null == input || "".equals(input.trim())) {
			return "";
		} else {
			return input.trim();
		}
	}

	/**
	 * 字符串转换为整型
	 * 
	 * @param input
	 * @return Integer,不是数字返回null
	 */
	public static Integer stringToInt(String input) {
		if (null != input && Validator.isNumber(input)) {
			return Integer.parseInt(input.trim());
		} else {
			return null;
		}
	}
	
	/**
	 * string转long
	 * @param input
	 * @return String不为数字，返回null
	 */
	public static Long stringToLong(String input){
		if(null != input && !"".equals(input.trim()) && Validator.isNumber(input)){
			return Long.valueOf(input.trim());
		}
		return null;
	}

	/**
	 * 整型转字符串
	 * 
	 * @param input
	 * @return String
	 */
	public static String intToString(int input) {
		return input + "";
	}

	/**
	 * 字符串转整型
	 * 
	 * @param input
	 * @return Double
	 */
	public static Double stringToFloat(String input) {
		if (Validator.isFloat(input)) {
			return Double.valueOf(input);
		} else {
			return null;
		}
	}

	/**
	 * 获取当前的默认格式化时间时间 yyyy-MM-dd HH:mm:ss
	 * 
	 * @return String
	 */
	public static String getCurrentSimpleDate() {
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sf.format(new Date());
	}

	/**
	 * 获取指点的当前格式化时间
	 * 
	 * @param format
	 *            例如(yyyy-MM-dd HH:mm:ss)
	 * @return String
	 */
	public static String getCurrentDateFormat(String format) {
		SimpleDateFormat sf = new SimpleDateFormat(format);
		return sf.format(new Date());
	}

	/**
	 * 获取工程的WebRoot路径
	 * 
	 * @param request
	 * @return String 例如：D:\soft_path\Tomcat6.0.29\webapps\microblog\
	 */
	public static String getRootPath(HttpServletRequest request) {
		return request.getSession().getServletContext().getRealPath("/");
	}

	/**
	 * 以逗号分隔的字符串转化为String []
	 * 
	 * @param input
	 * @return String []
	 */
	public static String[] stringToArray(String input) {
		if (null != input) {
			return input.trim().split(",");
		} else {
			return null;
		}
	}

	/**
	 * 以传入字符串分隔的字符串转化为String []
	 * 
	 * @param input
	 * @return String []
	 */
	public static List<String> stringToArray(String input, String target) {
		List<String> list = null;
		if (null != input && null != target) {
			String[] temp = input.trim().split(target);
			list = new ArrayList<String>();
			for (int i = 0, j = temp.length; i < j; i++) {
				if (!"".equals(temp[i].trim())) {
					list.add(temp[i]);
				}
			}
		}
		return list;
	}

	/**
	 * 过滤sql注入
	 * 
	 * @param sql
	 * @return
	 */
	public static String filterInjectionSQL(String sql) {
		return null == sql ? "" : sql.trim().replaceAll(";|-|'|xp_cmdshell|or", "");
	}

	/**
	 * 过滤html文件
	 * @param word
	 * @return
	 */
	public static String filterHTML(String word){
		if (null == word) {
			return "";
		} else {
			//
			return  word
					.trim()
					.replace("&", "&amp;")
					.replace("<", "&lt;")
					.replace(">","&gt;");
		}
	}
	/**
	 * 过滤所有的html标签
	 * @param inputString
	 * @return
	 */
	public static String filterHTMLText(String inputString) 
	 {
	        String htmlStr = inputString; //含html标签的字符串
	        String textStr ="";
	        java.util.regex.Pattern p_script;
	        java.util.regex.Matcher m_script;
	        java.util.regex.Pattern p_style;
	        java.util.regex.Matcher m_style;
	        java.util.regex.Pattern p_html;
	        java.util.regex.Matcher m_html;

	        try 
	        {
	         String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; //定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script> }
	         String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; //定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style> }
	         String regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式
	         String regEx_FONT = "<[\\s]*?FONT[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?FONT[\\s]*?>"; //定义HTML标签的正则表达式

	         p_script = Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);
	         m_script = p_script.matcher(htmlStr);
	         htmlStr = m_script.replaceAll(""); //过滤script标签
	     
	         
	         p_style = Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);
	         m_style = p_style.matcher(htmlStr);
	         htmlStr = m_style.replaceAll(""); //过滤style标签

            p_html = Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);
	         m_html = p_html.matcher(htmlStr);
	         htmlStr = m_html.replaceAll(""); //过滤html标签
	         
	         p_html = Pattern.compile(regEx_FONT,Pattern.CASE_INSENSITIVE);
	         m_html = p_html.matcher(htmlStr);
	         htmlStr = m_html.replaceAll(""); //过滤font标签
	         htmlStr=htmlStr.replaceAll("&nbsp;","");//滤除空格
	         textStr = htmlStr;
	        }
	        catch(Exception e) 
	        {
	         System.err.println("Html2Text: " + e.getMessage());
	        }
	        return textStr;//返回文本字符串
	       } 
	/**
	 * 获取classes目录的绝对路径
	 * 
	 * @return
	 */
	public static String getClassesPath() {
		return Tools.class.getResource("/").getPath().substring(1);
	}

	/**
	 * 根据int类型返回boolean类型。
	 * 
	 * @param value
	 * @return
	 */
	public static Boolean intToBoolean(int input) {
		return input == 0 ? false : true;
	}

	/**
	 * 过滤出博客内容中##之间的字符串内容 最复杂情况:####8888#88#9#99#3443#### 输出结果为:8888 9 3443
	 * 
	 * @param target
	 *            需要过滤的目标字符串
	 * @param list
	 *            过滤后的字符串集合
	 */
	final public static void substring(String target, List<String> list) {
		int start = target.indexOf("#");
		if (start > -1) {
			int end = target.indexOf("#", start + 1);
			if (end > -1) {
				String resultString = target.substring(start + 1, end).trim();
				if (null != resultString && !"".equals(resultString)) {
					list.add(resultString);
				}
				String newString = target.substring((start != end - 1) ? end + 1 : end);
				if (null != newString) {
					substring(newString, list);
				}
			}
		}
	}

	final public static String convertDate(String param) {
		String result = null;
		try {
			Date publishDate = null;;
			publishDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(param);
			Timestamp nowStamp = new Timestamp(new Date().getTime());
			long temp = nowStamp.getTime() - publishDate.getTime();

			/* 如果当前时间在发表时间之前 */
			if (nowStamp.before(publishDate)) {
				result = "1秒前";
			} else if (temp < 60 * 1000) {
				/* 小于一分钟 */
				result = (temp / 1000) > 0 ? temp / 1000 + "秒前" : "1秒前";
			} else if (6000 <= temp && temp < 3600000) {
				/* 小于一小时 */
				result = temp / (60000) + "分钟前";
			} else if (3600000 <= temp && temp < 86400000) {
				/* 小于一天 */
				String monthTemp = Integer.toString(Integer.parseInt(param.substring(5, 7)));
				String dayTemp = Integer.toString(Integer.parseInt(param.substring(8, 10)));
				String hourTemp = Integer.toString(Integer.parseInt(param.substring(11, 13)));
				String minTemp = Integer.toString(Integer.parseInt(param.substring(14, 16)));
				if (hourTemp.length() == 1) {
					hourTemp = "0" + hourTemp;
				}
				if (minTemp.length() == 1) {
					minTemp = "0" + minTemp;
				}
				result = monthTemp + "月" + dayTemp + "日 " + hourTemp + ":" + minTemp;
			} else if (86400000 <= temp && temp < 12 * 30 * 24 * 60 * 60 * 1000) {
				/* 小于一年&&大于一天 */
				String monthTemp = Integer.toString(Integer.parseInt(param.substring(5, 7)));
				String dayTemp = Integer.toString(Integer.parseInt(param.substring(8, 10)));
				String hourTemp = Integer.toString(Integer.parseInt(param.substring(11, 13)));
				String minTemp = Integer.toString(Integer.parseInt(param.substring(14, 16)));
				if (dayTemp.length() == 1) {
					dayTemp = "0" + dayTemp;
				}
				if (hourTemp.length() == 1) {
					hourTemp = "0" + hourTemp;
				}
				if (minTemp.length() == 1) {
					minTemp = "0" + minTemp;
				}
				if (monthTemp.length() == 1) {
					monthTemp = "0" + monthTemp;
				}
				result = monthTemp + "月" + dayTemp + "日 " + hourTemp + ":" + minTemp;
			} else {
				String yearTemp = param.substring(0, 4);
				String monthTemp = Integer.toString(Integer.parseInt(param.substring(5, 7)));
				String dayTemp = Integer.toString(Integer.parseInt(param.substring(8, 10)));
				String hourTemp = Integer.toString(Integer.parseInt(param.substring(11, 13)));
				String minTemp = Integer.toString(Integer.parseInt(param.substring(14, 16)));
				if (dayTemp.length() == 1) {
					dayTemp = "0" + dayTemp;
				}
				if (hourTemp.length() == 1) {
					hourTemp = "0" + hourTemp;
				}
				if (minTemp.length() == 1) {
					minTemp = "0" + minTemp;
				}
				if (monthTemp.length() == 1) {
					monthTemp = "0" + monthTemp;
				}
				/* 大于一年 */
				result = yearTemp + "年" + monthTemp + "月" + dayTemp + "日 " + hourTemp + ":" + minTemp;
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 过滤@me 提到我
	 * @param input
	 * @return
	 */
	public static String filterAtme(String input){
		//正则匹配数字，字母，下划线，减号，中文
		/*if(null != input && !"".equals(input.trim())){
			input = input.trim();
			String regex  = "(@([0-9a-zA-Z\\-_\\u4E00-\\u9FA5\\uF900-\\uFA2D]+))";
			return input.replaceAll(regex,"<a href='/microblog/otherAction.do?nickName=$2'>$1</a>");
		}*/
		String regex  = "(@([0-9a-zA-Z\\-_\\u4E00-\\u9FA5\\uF900-\\uFA2D]+))";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(input);
		while(m.find()){
			String atStr = m.group(1);
			String  str = m.group(2);
			String repStr = "<a href='/microblog/otherAction.do?nickName="+urlEncoder(str)+"'>"+atStr+"</a>";
			input = input.replace(atStr,repStr);
		}
		return input;
	}
	
	/**
	 * 编码字符串
	 * @param str
	 * @return
	 */
	public static String urlEncoder(String str){
		str = toTrim(str);
		try {
			str = URLEncoder.encode(str,"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return str;
	}
	
	/**
	 * 取指定长度的字符串 一个中文按两个字符计算
	 * 
	 * @param s
	 * @return
	 */
	public static String getChinessStr(String s, int len) {

		if (len >= s.getBytes().length) {
			return s;
		}
		int nums = 0;
		len -= 3;

		StringBuffer sb = new StringBuffer();
		char[] temp;
		temp = s.toCharArray();
		String str = "";		
		for (int i = 0; i < temp.length; i++) {
			str = String.valueOf(temp[i]);
			if (str.getBytes().length > 1)
				nums += 2;
			else
				nums++;
			sb.append(str);
			if (nums >= len)
				break;
		}
		return sb.toString();
	}
	/**
	 * 获取IP地址
	 * @param request
	 * @return
	 */
	public static  String getIp(HttpServletRequest request){
		return request.getRemoteAddr();
	}  
	
	/**
	 * 重定向
	 * @param response
	 * @param url
	 */
	public static void sendRedirect(HttpServletResponse response,String url){
		try {
			response.sendRedirect(url);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取地址栏url
	 * @param request
	 * @return
	 */
	public static String getLoginURL(HttpServletRequest request){
		return request.getRequestURL() + (request.getQueryString() == null ? "" : "?" + urlEncoder(request.getQueryString()));
	}
	
	/**
	 * 获取工程的WebRoot路径
	 * 
	 * @param request
	 * @return String 例如：F:\project\WebRoot
	 */
	public static String getWebRoot() {
		String root = System.getProperty("web.root");
		root = root.replace("\\","/");
		if(root.endsWith("/")) {
			root = root.substring(0,root.length()-1);
		}
		return root; 
	}
	
	/**
	 * 获取classes目录路径
	 * 如:F:/email3/WebRoot/WEB-INF/classes/
	 * @return
	 */
	public static String getClassPath() {
		String classPath = Tools.class.getResource("/").getPath().substring(1);
		if(classPath.startsWith("/")) {
			classPath = classPath.substring(1);
		}
		return classPath;
	}

	public static String getFormatDate(Date date,String format) {
		return new SimpleDateFormat(format).format(date);
	}
	
	public static String getSimpleDate(Date date) {
		return getFormatDate(date,Config.Date.FORMAT);
	}
	
	public static String getDefaultDate(){
		return getSimpleDate(new Date());
	}
}















